<template>
  <view class="content">
    <u--form
      labelPosition="left"
      labelWidth="65%"
      :model="model"
      :rules="rules"
      errorType="toast"
      ref="uForm"
    >
      <u-form-item class="item" :flexAble="false" className="img-formItem">
        <view class="item-left">头像</view>
        <view class="item-right">
          <view class="right-pic">
            <button
              class="avatar-wrapper"
              open-type="chooseAvatar"
              @chooseavatar="onChooseAvatar"
            >
              <image class="right-pic avatarUrl" :src="model.avatarUrl" />
            </button>
          </view>
          <view class="rightIcon">
            <u-icon
              class="rightIcon"
              slot="right"
              name="arrow-right"
              color="#c0c4cc"
              size="16"
            ></u-icon>
          </view>
        </view>
      </u-form-item>
      <u-form-item class="item">
        <view class="item-left">昵称</view>
        <view class="item-right">
          <u-input
            type="nickname"
            disabledColor="#fff"
            v-model="model.nickName"
            placeholder="获取昵称"
            @blur="onNicknameInput"
            border="none"
            input-align="right"
          />
          <view class="rightIcon">
            <u-icon
              class="rightIcon"
              slot="right"
              name="arrow-right"
              color="#c0c4cc"
              size="16"
            ></u-icon>
          </view>
        </view>
      </u-form-item>
      <u-form-item class="item" prop="real_name">
        <view class="item-left">用户名</view>
        <view class="item-right">
          <u-input
            disabledColor="#fff"
            v-model="model.real_name"
            placeholder="输入用户名"
            border="none"
            input-align="right"
          />
          <view class="rightIcon">
            <u-icon
              class="rightIcon"
              slot="right"
              name="arrow-right"
              color="#c0c4cc"
              size="16"
            ></u-icon>
          </view>
        </view>
      </u-form-item>
    
      <u-form-item class="item" prop="age">
        <view class="item-left">年龄</view>
        <view class="item-right">
          <u--input
            type="number"
            style="pointer-events: none"
            disabledColor="#fff"
            v-model="model.age"
            border="none"
            input-align="right"
            placeholder="请填写年龄"
          ></u--input>
          <view class="rightIcon">
            <u-icon
              class="rightIcon"
              slot="right"
              name="arrow-right"
              color="#c0c4cc"
              size="16"
            ></u-icon>
          </view>
        </view>
      </u-form-item>
      <u-form-item class="item" prop="phone">
        <view class="item-left">手机号</view>
        <view class="item-right">
          <view class="phone-box" v-if="user_id">
            <view class="phone-btn">
              <u-button
                class="phoneBtn"
                size="mini"
                open-type="getPhoneNumber"
                @getphonenumber="onGetPhoneNumber"
                >一键绑定</u-button
              >
            </view>
            <view class="rightIcon">
              <u-icon
                slot="right"
                name="arrow-right"
                color="#c0c4cc"
                size="16"
              ></u-icon>
            </view>
          </view>
          <view class="phone-box" v-else>
            <view class="phone-txt">{{ maskPhoneNumber(model.phone) }}</view>
            <view class="rightIcon">
              <u-button
                class="phoneBtn"
                size="mini"
                shape="circle"
                open-type="getPhoneNumber"
                @getphonenumber="onGetPhoneNumber"
                >更换</u-button
              >
            </view>
          </view>
        </view>
      </u-form-item>
      <u-form-item
        class="item"
        @click="handleCodeImg"
        :flexAble="false"
        className="img-formItem"
      >
        <view class="item-left">我的二维码</view>
        <view class="item-right">
          <!--					<image class="right-pic" :src="model.myCodePic" />-->
          <canvas canvas-id="qrcode" style="width: 60rpx; height: 60rpx" />
          <view class="rightIcon">
            <u-icon
              slot="right"
              name="arrow-right"
              color="#c0c4cc"
              size="16"
            ></u-icon>
          </view>
        </view>
      </u-form-item>
        <u-form-item
        class="item"
        @click="showSex = true"
        :flexAble="false"
        prop="sex"
        label="性别"
        :labelWidth="100"
        required
        customWidth
      >
        <u--input
          class="right-pic"
          v-model="model.sex"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择性别"
          border="none"
          input-align="right"
        ></u--input>
        <u-icon
          slot="right"
          name="arrow-right"
          color="#c0c4cc"
          size="16"
        ></u-icon>
      </u-form-item>
      <u-form-item
        class="item"
        required
        @click="goHref('facephoto')"
        :flexAble="false"
        customWidth
        className="img-formItem"
        prop="face_photo"
        label="上传人脸照片"
      >
        <view class="item-right">
          <image class="right-pic" :src="model.face_photo" />
          <u-icon
            slot="right"
            name="arrow-right"
            color="#c0c4cc"
            size="16"
          ></u-icon>
        </view>
      </u-form-item>
      <view class="tips-txt"></view>
      <view class="sub">
        <button @click="handleSave">保存</button>
      </view>
    </u--form>
    <u-action-sheet
      :show="showSex"
      :actions="actions"
      title="请选择性别"
      @close="showSex = false"
      @select="sexSelect"
    >
    </u-action-sheet>

    <!-- 隐私政策弹窗 -->
    <view v-if="showPrivacyPopup" class="privacy-mask">
      <view class="privacy-content">
        <view class="agreement" @click="toggleAgree">
          <view class="checkbox" :class="{ checked: isAgreed }"></view>
          <text>我已阅读并同意</text>
          <text class="policy" @click="navigateToPolicy">《隐私政策》</text>
        </view>

        <view class="button-group">
          <view class="btn disagree" @click="disagree">不同意</view>
          <view class="btn agree" @click="agree">同意</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request, requestData } from '@/utils/http.js'
import uQRCode from '@/common/uqrcode.js'
export default {
  data() {
    return {
      user_id: null,
      model: {
        id: '',
        sex: '',
        nickName: '',
        real_name: '',
        phone: '',
        age: '',
        avatarUrl: '',
        face_photo: '',
        myCodePic: '',
      },
      rules: {
        face_photo: {
          type: 'string',
          required: true,
          message: '请上传人脸照片',
          trigger: ['change'],
        },
        sex: {
          type: 'string',
          required: true,
          message: '请选择性别',
          trigger: ['change'],
        },
      },
      actions: [
        {
          name: '男',
          value: 1,
        },
        {
          name: '女',
          value: 2,
        },
      ],
      showSex: false,
      showPrivacyPopup: false,
      isAgreed: false,
    }
  },
  onLoad() {
    this.makeQrcode()
    this.initUesrInfo() //初始info
    this.$refs.uForm.setRules(this.rules)
  },
  onShow() {},
  onReady() {},
  methods: {
    //手机号替换中间4位为星号
    maskPhoneNumber(phoneNumber) {
      if (phoneNumber.length === 11) {
        return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      } else {
        return '手机号格式不正确'
      }
    },

    //初始info
    initUesrInfo() {
      request('/user/info/get', {})
        .then((res) => {
          let sex = res?.datas?.gender
          let sexLabel = ''
          if (sex == 1) {
            sexLabel = '男'
          } else if (sex == 2) {
            sexLabel = '女'
          }
          this.model = {
            ...this.model,
            ...{
              id: res?.datas?.user_id || '',
              nickName: res?.datas?.nick_name || '',
              real_name: res?.datas?.real_name || '',
              sex: sexLabel,
              age: res?.datas?.age?.toString() || '',
              phone: res?.datas?.mobile || '',
              avatarUrl:
                res?.datas?.avatar_url ||
                require('@/static/img/default-avatar.png'),
              face_photo: res?.datas?.face_photo,
              myCodePic:
                uni.getStorageSync('myCodePic') ||
                require('@/static/img/my-qrcode-default.png'),
            },
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },

    // 表单提交
    handleSave() {
      let user_id = uni.getStorageSync('user_id')
      let face_photo = this.model.face_photo
      console.log('face_photo', face_photo)
      if (!face_photo) {
        uni.showToast({
          title: '请先绑上传人脸照片',
          icon: 'none',
        })
        return
      }
      if (!user_id) {
        uni.showToast({
          title: '请先绑定手机号',
          icon: 'none',
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/loginPhone/loginPhone',
          })
        }, 1000)
      } else {
        this.$refs.uForm
          .validate()
          .then((res) => {
            let sexLabel = this.model.sex
            let gender = ''
            if (sexLabel == '男') {
              gender = 1
            } else if (sexLabel == '女') {
              gender = 2
            } else if (sex == '未知') {
              gender = 0
            }

            request('/user/info/update', {
              gender,
              age: Number(this.model.age),
              nick_name: this.model.nickName,
              real_name: this.model.real_name,
              avatar_url: this.model.avatarUrl,
            })
              .then((res) => {
                if (res.code == 0) {
                  uni.$u.toast('保存成功')
                  this.initUesrInfo() //初始info
                  uni.setStorageSync('avatarUrl', res?.datas?.avatar_url)
                  uni.setStorageSync('mobile', res?.datas?.mobile)
                  uni.setStorageSync('nickName', res?.datas?.nick_name)
                } else {
                  uni.$u.toast('保存失败')
                }
              })
              .catch((err) => {
                console.log(err)
              })
          })
          .catch((errors) => {
            //uni.$u.toast('校验失败')
          })
      }
    },

    //选择性别
    sexSelect(e) {
      this.model.sex = e.name
      this.$refs.uForm.validateField('sex')
    },

    //手机号
    onGetPhoneNumber(e) {
      const {
        detail: { encryptedData, iv, code },
      } = e
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        let open_id = uni.getStorageSync('open_id')
        let access_token = uni.getStorageSync('access_token')
        request('/wxaccess/mp/user/getPhoneNumber', {
          wxphone_code: code,
          open_id: open_id,
        })
          .then((res) => {
            console.log(res)
            uni.setStorageSync('open_id', res?.datas?.open_id || '')
            uni.setStorageSync('user_id', res?.datas?.user_id || '')
            uni.setStorageSync('access_token', res?.datas?.access_token || '')
            uni.setStorageSync('mobile', res?.datas.mobile || 0)
          })
          .catch((err) => {
            uni.showToast({
              title: err,
              duration: 2000,
              icon: 'none',
            })
          })
      } else {
        uni.showToast({
          title: '为了给您提供更好的服务，请同意获取手机号！',
          duration: 2000,
          icon: 'none',
        })
      }
    },

    //头像
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
          filePath: url,
          encoding: 'base64',
          success: (data) => {
            let str = data.data
            resolve(str)
          },
          fail: (err) => {
            uni.showToast({
              title: JSON.stringify(err),
              icon: 'none',
            })
          },
        })
      })
    },
    async onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      try {
        let baseImg = await this.uploadFilePromise(avatarUrl)
        request('/user/avatar/base64image/upload', {
          user_id: uni.getStorageSync('user_id'),
          image_base64: baseImg,
          image_ext: 'jpg',
        })
          .then((res) => {
            if (res.code == 0) {
              console.log(res)
              this.model.avatarUrl = res.datas.url
              uni.setStorageSync('avatarUrl', res?.datas?.url)
            } else {
            }
          })
          .catch((err) => {
            console.log(err)
          })
      } catch (err) {
        console.log(err)
      }
    },

    //昵称
    onNicknameInput(val) {
      this.model.nickName = val
      uni.setStorageSync('nickName', val || '')
    },

    //人脸识别
    goHref(txt) {
      if (txt == 'facephoto') {
        this.showPrivacyPopup = true
      }
    },

    // 生成二维码
    makeQrcode() {
      uQRCode.make({
        canvasId: 'qrcode',
        componentInstance: this,
        text: 'biz=user&user_id=' + uni.getStorageSync('user_id'),
        size: 33,
        margin: 0,
        backgroundColor: '#ffffff',
        foregroundColor: '#000000',
        fileType: 'jpg',
        errorCorrectLevel: uQRCode.errorCorrectLevel.H,
        success: (res) => {},
      })
    },
    //隐私
    toggleAgree() {
      this.isAgreed = !this.isAgreed
    },
    navigateToPolicy(event) {
      event.stopPropagation()
      uni.navigateTo({
        url: '/pagesC/privacyPolicy/index',
      })
    },
    agree() {
      if (this.isAgreed) {
        this.showPrivacyPopup = false
        uni.navigateTo({
          url: '/pagesC/userFacephoto/index',
        })
      } else {
        uni.showToast({
          title: '请先阅读并同意隐私政策',
          icon: 'none',
        })
      }
    },
    disagree() {
      // 不同意处理逻辑
      uni.showToast({
        title: '需要同意隐私政策才能使用',
        icon: 'none',
      })
      this.showPrivacyPopup = false
    },

    //点击我的二维码
    handleCodeImg() {},
  },
}
</script>

<style lang="scss" scoped>
/* 更改form样式
	https://gitcode.csdn.net/65ec454d1a836825ed795f5b.html?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NTIxMDQ4LCJleHAiOjE3MjQwNTQxMzUsImlhdCI6MTcyMzQ0OTMzNSwidXNlcm5hbWUiOiJxcV8zMzMzMjE4NCJ9.oGTHEemmtk-LQyb8Q8wT6vnYMGpHcw0g2D1P3RXuFXE
	 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f7f7f8;
  // background: #f8f8f8;
}

.vue-ref {
  width: 100%;
}

.u-form {
  width: 100%;
  height: auto;
  padding: 0 20rpx;
  box-sizing: border-box;
}

::v-deep .u-form-item {
  width: 100% !important;
  height: 100% !important;
  box-sizing: border-box !important;
  font-size: 32rpx !important;
  // background: red !important;
}

::v-deep .u-form .u-form-item__body__right {
  flex-direction: row !important;
}

::v-deep .u-form-item__body__right__content__slot {
  flex-direction: row !important;
  width: 100%;
}

::v-deep .u-form-item__body__right_no_flex {
  width: 100% !important;
  height: 100% !important;
}

::v-deep .u-form-item__body {
  padding: 0 !important;
  height: 100% !important;
}

.item {
  width: 100%;
  padding: 0 20rpx;
  box-sizing: border-box;
  height: 100rpx;
  background: #fff;
  border-bottom: 1px solid #f5f5f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .item-left {
    width: 30%;
    display: flex;
    align-items: center;
    padding-left: 20rpx;
    // font-size: 28rpx;
  }

  .item-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 14rpx;
  }
}

.right-txt {
}

.rightIcon {
  margin-left: 20rpx;
}

.right-pic {
  width: 60rpx;
  height: 60rpx;
  display: block;
  margin-right: 10rpx;
}

.avatarUrl {
  border-radius: 50%;
}

.avatar-wrapper {
  padding: 0;
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
}

.avatar {
  display: block;
  width: 100%;
  height: 100%;
}

.container {
  display: flex;
}

.u-form-item__body__right__message {
  margin-left: 0;
}

::v-deep .u-button--info {
  background: $global-color-golden !important;
  width: 130rpx !important;
  z-index: 999;
  color: #fff !important;
  // border-radius: 20rpx !important;
}
::v-deep .u-form-item__body__left__content__label{
  font-size: 32rpx!important;
}

.phone-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.sub {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 60rpx;
}

.sub button {
  border: none;
  width: 90%;
  height: 70rpx;
  line-height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: $global-color-golden;
  border-radius: 35rpx;
  color: #fff;
  font-weight: 400;
}

// .item-right-data {
// 	padding-right: 50rpx;
// }

.phone-txt {
  font-size: 28rpx;
}

::v-deep .u-form-item__body__right__message {
  margin-left: 20rpx !important;
}

/* 遮罩层 */
.privacy-mask {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 9999;
}

/* 内容区域 */
.privacy-content {
  background: #fff;
  width: 100%;
  padding: 30rpx;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: 80rpx;
}

/* 协议文字 */
.agreement {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  padding: 20rpx 0;
}

/* 自定义复选框 */
.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  margin-right: 15rpx;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.checkbox.checked {
  background: #d5ad57;
  border-color: #d5ad57;
}

.checkbox.checked::after {
  content: '';
  position: absolute;
  left: 10rpx;
  top: 6rpx;
  width: 8rpx;
  height: 16rpx;
  border: solid white;
  border-width: 0 4rpx 4rpx 0;
  transform: rotate(45deg);
}

/* 隐私政策文字 */
.policy {
  color: #d5ad57;
  margin-left: 8rpx;
}

/* 按钮组 */
.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.btn {
  width: 260rpx;
  height: 70rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.disagree {
  background: #f0f0f0;
  color: #666;
  margin-right: 20rpx;
}

.agree {
  background: #d5ad57;
  color: white;
}
</style>
